import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入登陆注册组件
import Reg from '@/views/Reg/Reg.vue'
import Login from '@/views/Login/Login.vue'
import Main from '@/views/Main/Main.vue'
import store from '@/store'
import Home from '@/views/Menus/Home/Home.vue'
import UserInfo from '@/views/Menus/User/UserInfo.vue'
import UserAvatar from '@/views/Menus/User/UserAvatar.vue'
import UserPwd from '@/views/Menus/User/UserPwd.vue'
import ArtCate from '@/views/Menus/Article/ArtCate.vue'
import ArtList from '@/views/Menus/Article/ArtList.vue'

Vue.use(VueRouter)

// 声明路由规则
const routes = [
  { path: '/reg', component: Reg },
  { path: '/login', component: Login },
  {
    path: '/',
    component: Main,
    redirect: '/home', // 路由重定向
    children: [
      // 一般情况下子路由不以 / 开头，因为不加 / 会拼接前面的父路由
      // 如果非要以 / 开头，则不拼接前面的父路由 /home
      { path: '/home', component: Home },
      { path: '/user-info', component: UserInfo },
      { path: '/user-avatar', component: UserAvatar },
      { path: '/user-pwd', component: UserPwd },
      { path: '/art-cate', component: ArtCate },
      { path: '/art-list', component: ArtList }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 添加全局前置守卫
// 注意事项: 必须要调用 next() 否则就瘫痪了
// to: 到哪里去
// from: 从哪里来
// next: 是否放行，放行: next() 不放行: next(false) 强制跳转: next('路径')
router.beforeEach((to, from, next) => {
  // 需求: 如果没有登陆就不允许去首页
  // 登陆的判断依据：是否有 token
  const token = store.state.user.token
  // console.log(to, from)

  const whiteList = ['/login', '/reg']

  // 条件1：没登录
  // 条件2 & 3:去的页面既不是登录也不是注册
  // whiteList.includes: 数组方法，判断指定的元素是否在数组中，返回一个布尔值
  // whiteList.indexOf('/404') -1
  if (!token && !whiteList.includes(to.path)) {
    // 打回登录页
    next('/login')
    // 提醒用户未登录
    Vue.prototype.$message.error('您还未登录哦！亲！')
  } else {
    next()
  }
})

export default router
